package com.example.forum.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParserBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.buf.UEncoder;
import org.springframework.util.StringUtils;

import javax.crypto.SecretKey;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Slf4j
public class JWTUtils {
    public static final long Expiration=60*60*1000;
    //密钥
    private static final String secretString="f/qzx3qcpKBTijZmc7T3p6QJYtg+X3420mgq7QMYIIc=";

    //生成安全密钥
    private static final SecretKey KEY = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretString));

    /**
     * 生成token
     * @param claim
     * @return
     */
    public static String genJwt(Map<String,Object> claim){
        //⾃定义信息
        String jwt = Jwts.builder()
                .setClaims(claim) //⾃定义内容(负载)
                .setIssuedAt(new Date()) // 设置签发时间
                .setExpiration(new Date(System.currentTimeMillis() + Expiration)) //设置过期时间
                .signWith(KEY) //签名算法
                .compact();
        return jwt;
    }

    /**
     * 验证token
     */
    public static Claims parseJwt(String jwt) {
        if(!StringUtils.hasLength(jwt)) {
            return null;
        }
        //创建解析器，设置签名密钥
        JwtParserBuilder jwtParserBuilder = Jwts.parserBuilder().setSigningKey(KEY);
        Claims claims = null;
        try{
            claims = jwtParserBuilder.build().parseClaimsJws(jwt).getBody();
        }catch (Exception e) {
            //签名验证失败
            log.error("解析令牌错误: "+e);
        }
        return claims;
    }

    /**
     * 从token中拿用户id
     * @param jwt
     * @return
     */
    public static String getUserId(String jwt) {
        Claims claims = JWTUtils.parseJwt(jwt);
        if(claims != null) {
            Map<String,Object> user = new HashMap<String, Object>(claims);
            return (String)user.get("id");
        }
        return null;
    }

    public static String getJwt(HttpServletRequest request) {
        return request.getHeader("user_token");
    }

}
